import re
from docx import Document
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
import pandas as pd


def get_phone_numbers(text):
    # 正则表达式匹配电话号码
    # 区号3~4位，固定电话7位，手机号11位
    pattern = r'(\b\d{3,4}-\d{7,8}\b|\b\d{11}\b|\b\d{7,8}\b)'
    phone_numbers = re.findall(pattern, text)
    return phone_numbers


def getphonenum(docxfile, xlsxfile):
    # 读取Word文档
    doc = Document(docxfile)

    # 提取文本
    full_text = []
    for para in doc.paragraphs:
        full_text.append(para.text)
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                full_text.append(cell.text)

                # 使用正则表达式找出电话号码
    phone_numbers = get_phone_numbers(' '.join(full_text))

    # 将电话号码写入DataFrame
    df = pd.DataFrame(phone_numbers, columns=['PhoneNumber'])

    # 如果xlsxfile已存在，则追加数据；否则创建新的Excel文件
    if os.path.exists(xlsxfile):
        # 读取现有Excel文件
        wb = openpyxl.load_workbook(xlsxfile)
        ws = wb.active

        # 追加数据到现有工作表（这里假设第一列是电话号码）
        for row in dataframe_to_rows(df, index=False, header=False):
            ws.append(row)

            # 保存更改
        wb.save(xlsxfile)
    else:
        # 创建新的Excel文件
        wb = Workbook()
        ws = wb.active
        ws.title = "PhoneNumbers"

        # 写入数据到新的工作表
        for row in dataframe_to_rows(df, index=False, header=True):
            ws.append(row)

            # 保存文件
        wb.save(xlsxfile)

getphonenum('example.docx', 'phone_numbers.xlsx')